﻿Imports System.Data.OleDb
Public Class EditProfile
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack Then
            Return
        End If

        Dim sql As String = "SELECT * FROM UserProfile WHERE DinerId=@f6"
        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("WarriorConnection").ConnectionString)
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
        cmd.Parameters.AddWithValue("@f6", User.Identity.Name)

        conn.Open()
        Dim dr = cmd.ExecuteReader()
        dr.Read()
        If Not IsDBNull(dr("FirstName")) Then tb_FirstName.Text = dr("FirstName")
        If Not IsDBNull(dr("LastName")) Then tb_LastName.Text = dr("LastName")
        If Not IsDBNull(dr("Gender")) Then rbl_Gender.SelectedValue = dr("Gender")
        If Not IsDBNull(dr("DateOfBirth")) Then cld_DOB.SelectedDate = dr("DateOfBirth")
        conn.Close()

    End Sub

    Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_Submit.Click
        Dim newFileName As String
        newFileName = Guid.NewGuid().ToString() & getSuffix(fup_Portrait.FileName)
        If fup_Portrait.HasFile Then
            fup_Portrait.SaveAs(Server.MapPath("Images/Portrait") & "/" & newFileName)
        End If

        Dim sql As String

        If fup_Portrait.HasFile Then
            sql = "UPDATE UserProfile SET FirstName=@f1, LastName=@f2, Portrait=@f3, DateOfBirth=@f4, Gender=@f5 WHERE DinerId=@f6"
        Else
            sql = "UPDATE UserProfile SET FirstName=@f1, LastName=@f2, DateOfBirth=@f4, Gender=@f5 WHERE DinerId=@f6"
        End If
        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("WarriorConnection").ConnectionString)
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)

        cmd.Parameters.AddWithValue("@f1", tb_FirstName.Text)
        cmd.Parameters.AddWithValue("@f2", tb_LastName.Text)
        If fup_Portrait.HasFile Then cmd.Parameters.AddWithValue("@f3", "Images/Portrait/" & newFileName)
        cmd.Parameters.AddWithValue("@f4", cld_DOB.SelectedDate.Date)
        cmd.Parameters.AddWithValue("@f5", rbl_Gender.SelectedValue)
        cmd.Parameters.AddWithValue("@f6", User.Identity.Name)
        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()
        cmd.Dispose()
        conn.Dispose()
    End Sub

    Function getSuffix(ByVal fn As String)
        Dim fileParts = fn.Split(".")
        Dim suffix = fileParts(fileParts.Length - 1)
        Return "." & suffix
    End Function
End Class